class ResampleAudioProcessor extends AudioWorkletProcessor {
  constructor() {
    super();
    this.targetSampleRate = 16000;
    this.inputBuffer = [];
    // 初始重采样比例 后面会被函数更改正确
    this.ratio = 1;
    this.needsResampling = true;
    // console.log("🤖: 我发现这采样率是", sampleRate);
    // if (sampleRate === this.targetSampleRate) {
    //   console.log("🤖: 直接跳过重采样吧");
    // }
  }

  resample(input) {
    const inputLength = input.length;
    const outputLength = Math.ceil(inputLength / this.ratio);
    const output = new Float32Array(outputLength);

    for (let i = 0; i < outputLength; i++) {
      const sourcePosition = i * this.ratio;
      const index1 = Math.floor(sourcePosition);
      const index2 = Math.min(index1 + 1, inputLength - 1);

      const sample1 = input[index1];
      const sample2 = input[index2];
      const weight = sourcePosition - index1;

      output[i] = sample1 + weight * (sample2 - sample1);
    }

    return output;
  }

  // inputs outputs 是相对于音频处理图的
  process(inputs, outputs, _parameters) {
    if (inputs.length === 0 || inputs[0].length === 0) return true;

    const input = inputs[0][0]; // 假设单声道输入
    // console.log("接收到音频数据: ", input);
    // sampleRate 是 AudioWorklet 自带变量
    // REF: https://developer.mozilla.org/en-US/docs/Web/API/AudioWorkletGlobalScope/sampleRate
    this.ratio = sampleRate / this.targetSampleRate;

    this.needsResampling = sampleRate !== this.targetSampleRate;

    this.inputBuffer.push(...input);

    const outputLength = Math.ceil(this.inputBuffer.length / this.ratio);
    if (outputLength > 0) {
      let resampledData;

      if (this.needsResampling) {
        resampledData = this.resample(this.inputBuffer);
      } else {
        // 跳过重采样
        resampledData = new Float32Array(this.inputBuffer);
      }

      this.port.postMessage({ audio: resampledData.buffer });

      // 更新缓冲区
      if (this.needsResampling) {
        this.inputBuffer = this.inputBuffer.slice(
          resampledData.length * this.ratio,
        );
      } else {
        // 如果不需要重采样，直接清空缓冲区
        this.inputBuffer = [];
      }
    }

    // 清空 outputs（因为不需要播放到扬声器）
    for (let channel = 0; channel < outputs[0].length; channel++) {
      outputs[0][channel].fill(0); // 将所有通道的输出置为静音
    }

    return true;
  }
}

// 注册
try {
  registerProcessor("resample-audio-processor", ResampleAudioProcessor);
} catch (error) {
  console.error("😨: 竟然音频节点注册失败", error);
}
